package com.qf09;


import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteDemo {
    //创建读写锁
    private ReentrantReadWriteLock rrl = new ReentrantReadWriteLock();
    //获取读锁
    ReentrantReadWriteLock.ReadLock readLock = rrl.readLock();
    //获取写锁
    ReentrantReadWriteLock.WriteLock writeLock = rrl.writeLock();

    private String value;

    //读取
    public String getValue() {
        //使用读锁上锁
        readLock.lock();
        try {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("读取:"+value);
            return value;
        } finally {
            readLock.unlock();
        }
    }

    //写入
    public void setValue(String value) {
        writeLock.lock();
        try{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("写入:"+value);
            this.value = value;
        }finally {
            writeLock.unlock();
        }
    }
}
